<?php
namespace Com\Pay;

//越腾支付

class YueTengPay{

    private $config = array();

    public function __construct($mchData){
        $this->config = $mchData;
    }

    /*生成支付连接*/
    public function getUrl($order_info){
        $merchantCode = $this->config['mch_id'];
        $notifyUrl = S_URL . '/Api/NotifyCallback/YuetengPayNoyify';
        $order_sn = $order_info['ordernumber'];
        $price = $order_info['paymoney'];
        $post_data = array(
            "out_order_sn" => $order_sn,
            'title' => "CBPAY",
            'pay_type' => $order_info['pay_type'],
            'mch_id' => $merchantCode,
            'amount_fee' => $price,
            'sign_type' => "MD5",
            'notify_url' => $notifyUrl,
            'return_url' => $order_info['return_url'],
            'nonce_str' => mt_rand(11111111111,999999999999),
        );
        $post_data['sign'] = $this->setParam($post_data , $this->config['mch_key'] , false);
        $Send_url = 'https://pay.new314.com/unifiOrder';
        $result = https_request($Send_url , $post_data);
        $r = json_decode($result,  true);
        if($r['result_code'] == 0){
            return $r['token_id'];
        }
        return '';
    }

    private function setParam($param,$key,$IS_Notify){
        $str = "";
        ksort($param);
        foreach($param as $key1=>$val)  {
            if($val == '' || ($IS_Notify && $key1 == 'sign')) continue;
            $str.=$key1."=".$val."&";
        }
        $str = rtrim($str,'&');
        $sign = strtoupper(md5($str . '&key=' . $key));
        return $sign;
    }


    //回调方法，把返回数据处理成统一规定返回
    public function response(){
        $data = parseData();
        // 进行签名验证
        $CheckSignStatus =  $this->setParam($data,$this->config['mch_key'], true);
        if($data['sign'] == $CheckSignStatus){
            // 验签成功
            if($data['result_code'] == '0'){
                return true;
            }else{
                return false;
            }
        }else{
            // 失败
            return false;
        }
    }

}
